package org.sanm.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

public class JsonMapTypeHandler<T> extends BaseTypeHandler<Map<String, T>> {


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Map<String, T> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, toJson(parameter));
    }

    @Override
    public Map<String, T> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return this.parseJson(rs.getString(columnName));
    }

    @Override
    public Map<String, T> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return this.parseJson(rs.getString(columnIndex));
    }

    @Override
    public Map<String, T> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return this.parseJson(cs.getString(columnIndex));
    }

    private String toJson(Map<String, T> map) {
        try {
            return new ObjectMapper().writeValueAsString(map);
        } catch (JsonProcessingException e) {
            throw new RuntimeException();
        }
    }

    private Map<String, T> parseJson(String json) {
        if (json == null || json.isEmpty()) {
            return null;
        }
        try {
            return new ObjectMapper().readValue(json, new TypeReference<Map<String, T>>() {
            });
        } catch (JsonProcessingException e) {
            throw new RuntimeException();
        }
    }
}
